package com.bk.cyxf.lf;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import jt.classic.system.ISystem;
import jt.classic.system.object.IObject;
import jt.classic.system.object.ObjectManager;
import jt.classic.system.purview.PurviewManager;
import jt.classic.system.role.IRole;
import jt.classic.system.role.RoleManager;
import jt.classic.system.user.IUser;

import org.limp.basework.MachiningException;
import org.limp.basework.SimpleBean;
import org.limp.basework.SimpleBean4Table;
import org.limp.basework.SimpleBeanMachining;
import org.limp.basework.Table;
import org.limp.basework.impl.SimpleBean4TableImpl;
import org.limp.basework.tools.BaseworkUtil;
import org.limp.mine.DataTrimmerI;
import org.limp.mine.StringTool;

import com.bk.cyxf.log.LogManager;


/**
 * 来访对象处理插件类
 *
 * @author lvt
 *
 */
public class QtfObjectHandler implements SimpleBeanMachining {
    public SimpleBean machining(SimpleBean bean, Table table,
        HttpServletRequest request, Connection conn, int type)
        throws MachiningException {
        // TODO Auto-generated method stub
        if (type == 0) {
            IObject obj = (IObject) bean.getResource().get("OBJECT");

            Table tbl = obj.iobject().itable("APP_QTF");

            if (tbl == null) {
                throw new MachiningException(
                    "QtfObjectHandler exception for save object, table 'APP_QTF' is null.");
            }

            Map info = (Map) ((List) obj.icontent(tbl)).get(0);

            /*来访类型*/
            String LFTYPE = StringTool.checkString(info.get("LFTYPE"));
            
            String lfid = StringTool.checkString(info.get("QTFID"));
            String SSDNAMEFULLNAME = StringTool.checkString(info.get("SSDNAME"));
            
            int idx = SSDNAMEFULLNAME.indexOf("-");
            int idx2 = SSDNAMEFULLNAME.lastIndexOf(">");
            String SSDNAME = SSDNAMEFULLNAME.substring(0, idx);
            String prix = "";
            //具体社区名
            String sq = SSDNAMEFULLNAME.substring(idx2+1);
            if (LFTYPE.equals("0")) {
                /*街乡*/
            	prix = "街乡/"+SSDNAME + "/";
            } else if (LFTYPE.equals("1")) {
                /*区*/
            	prix = "朝阳区政府/"+SSDNAME + "/";
            }
            String xbgroupid = StringTool.checkString(info.get(
            "XBDWID"));

			String xbgroupname = StringTool.checkString(info.get(
			            "XBDWNAME"));
			
			String[] idArray = xbgroupid.split(",");
			String[] nameArray = xbgroupname.split(",");
			
			
			BaseworkUtil util = new BaseworkUtil();
			PurviewManager pm = new PurviewManager(conn);
			RoleManager rm = new RoleManager(conn);
			ObjectManager manager = new ObjectManager(conn);
			try {
			
			
			for(int i= 0;i <nameArray.length && nameArray.length>0;i++){
				
			    /*派遣科室办理*/
			    SimpleBean4Table sbt1 = new SimpleBean4TableImpl(
			            "APP_XFHANDLER");
			    if("社区/行政村".equals(nameArray[i])){
			    	
			    	List<Map> groupList = searchMultiDept(conn,prix+sq);
			    	for(Map m : groupList){
			    		/*添加处理科室ID*/
					    sbt1.getResource().put("H_GROUPID", m.get("ID"));
					
					    /*添加处理科室名称*/
					    sbt1.getResource().put("H_GROUPNAME", m.get("NAME"));
					
					    sbt1.getResource().put("XFID", lfid);
					    sbt1.getResource().put("XF_TYPE", "2");
					    sbt1.getResource().put("H_STATUS", "0");
					
					    
					    Map rsm = util.manualSave1(sbt1, conn);
					
					    manager.createSystemRelationObject(obj.id(),
					        "APP_XFHANDLER", (String) rsm.get("HID"));
			    		
			    	}
			    	
			    }else{
			    	Map<String,String> groupMap = searchSingleDept(conn,prix+nameArray[i]);
			    	
			    	if(groupMap != null){
			    		
			    		/*添加处理科室ID*/
					    sbt1.getResource().put("H_GROUPID", groupMap.get("ID"));
					
					    /*添加处理科室名称*/
					    sbt1.getResource().put("H_GROUPNAME", groupMap.get("NAME"));
					
					    sbt1.getResource().put("XFID", lfid);
					    sbt1.getResource().put("XF_TYPE", "2");
					    sbt1.getResource().put("H_STATUS", "0");
					
					    
					    Map m = util.manualSave1(sbt1, conn);
					
					    manager.createSystemRelationObject(obj.id(),
					        "APP_XFHANDLER", (String) m.get("HID"));
			    	}
			    	
			    	
			    }
			    
			
			    
			}

			} catch (Exception ex) {
	            ISystem.catchException(request, this, ex);
	        }
			
            IRole role = null;

            if (LFTYPE.equals("0")) {
                /*街乡来信由街乡信访办人员统一办理*/
                role = rm.getRoleByKey("jxxfbuser");
            } else if (LFTYPE.equals("1")) {
                /*区来信由街乡信访办人员统一办理*/
                role = rm.getRoleByKey("quxfbuser");
            }

            /*信访系统管理员*/
            IRole xfManager = rm.getRoleByKey("xfmanager");

            IUser user = ISystem.getSessionUser(request);


            try {
                /*对信访办角色进行授权,可以对该来访进行办理*/
                pm.insert(obj.id(), obj.iname(), obj.ikey(), "ISYS_OBJECT", 3,
                    role.id(), role.iname(), "role", user, false);

                /*对信访系统管理员角色进行授权,可以对来信进行编辑\删除\查阅*/
                pm.insert(obj.id(), obj.iname(), obj.ikey(), "ISYS_OBJECT", 3,
                    xfManager.id(), xfManager.iname(), "role", user, false);
            } catch (Exception ex) {
                throw new MachiningException("purview for object error.", ex);
            }

            try {
                LogManager lm = new LogManager(conn);
                lm.log(user, lfid, "2", "qtfdj", "");
            } catch (Exception ex) {
                throw new MachiningException("log lfdj error.", ex);
            }
            


        }else if (type == 1) {
            IObject obj = (IObject) bean.getResource().get("OBJECT");

            Table tbl = obj.iobject().itable("APP_QTF");

            if (tbl == null) {
                throw new MachiningException(
                    "QtfObjectHandler exception for save object, table 'APP_QTF' is null.");
            }

            Map info = (Map) ((List) obj.icontent(tbl)).get(0);

            /*来访类型*/
            String LFTYPE = StringTool.checkString(info.get("LFTYPE"));
            
            String lfid = StringTool.checkString(info.get("QTFID"));
            String SSDNAMEFULLNAME = StringTool.checkString(info.get("SSDNAME"));
            
            int idx = SSDNAMEFULLNAME.indexOf("-");
            int idx2 = SSDNAMEFULLNAME.lastIndexOf(">");
            String SSDNAME = SSDNAMEFULLNAME.substring(0, idx);
            String prix = "";
            //具体社区名
            String sq = SSDNAMEFULLNAME.substring(idx2+1);
            if (LFTYPE.equals("0")) {
                /*街乡*/
            	prix = "街乡/"+SSDNAME + "/";
            } else if (LFTYPE.equals("1")) {
                /*区*/
            	prix = "朝阳区政府/"+SSDNAME + "/";
            }
            
            String xbgroupid = StringTool.checkString(info.get(
            "XBDWID"));

			String xbgroupname = StringTool.checkString(info.get(
			            "XBDWNAME"));
			
			String[] idArray = xbgroupid.split(",");
			String[] nameArray = xbgroupname.split(",");
			
			
			BaseworkUtil util = new BaseworkUtil();
			PurviewManager pm = new PurviewManager(conn);
			RoleManager rm = new RoleManager(conn);
			ObjectManager manager = new ObjectManager(conn);
			
			
//			try {
//				Map xfblInfo = (Map) ((List) obj.icontent(obj.iobject().itable(
//						"APP_XFHANDLER"))).get(0);
//
//				SimpleBean4Table sbt = new SimpleBean4TableImpl("APP_XFHANDLER");
//				sbt.reload(xfblInfo);
//
//				util.manualDelete1(sbt, conn);
//
//				manager.removeSystemRelationObject(obj.id(), obj.iobject().itable(
//						"APP_XFHANDLER"));
//			} catch (Exception ex) {
//				throw new MachiningException("remove qtfbl-empty-info error.",
//						ex);
//			}
			
			List<Map> xfblInfoList = (List) obj.icontent(obj.iobject().itable(
			"APP_XFHANDLER"));
			
			try {
			for(int i= 0;i <nameArray.length && nameArray.length>0;i++){
				
			    /*派遣科室办理*/
			    SimpleBean4Table sbt1 = new SimpleBean4TableImpl(
			            "APP_XFHANDLER");
			    
			    if("社区/行政村".equals(nameArray[i])){
			    	
			    	List<Map> groupList = searchMultiDept(conn,prix+sq);
			    	for(Map m : groupList){
			    		/*添加处理科室ID*/
					    sbt1.getResource().put("H_GROUPID", m.get("ID"));
					
					    /*添加处理科室名称*/
					    sbt1.getResource().put("H_GROUPNAME", m.get("NAME"));
					
					    sbt1.getResource().put("XFID", lfid);
					    sbt1.getResource().put("XF_TYPE", "2");
					    sbt1.getResource().put("H_STATUS", "0");
					
					    
					    if(!isAlreadyExist(xfblInfoList,sbt1)){
					    	Map rsm = util.manualSave1(sbt1, conn);
					    	manager.createSystemRelationObject(obj.id(),"APP_XFHANDLER", (String) rsm.get("HID"));
					    }
			    		
			    	}
			    	
			    }else{
			    	Map<String,String> groupMap = searchSingleDept(conn,prix+nameArray[i]);
			    	
			    	if(groupMap != null){
			    		
			    		/*添加处理科室ID*/
					    sbt1.getResource().put("H_GROUPID", groupMap.get("ID"));
					
					    /*添加处理科室名称*/
					    sbt1.getResource().put("H_GROUPNAME", groupMap.get("NAME"));
					
					    sbt1.getResource().put("XFID", lfid);
					    sbt1.getResource().put("XF_TYPE", "2");
					    sbt1.getResource().put("H_STATUS", "0");
					
					    
					    if(!isAlreadyExist(xfblInfoList,sbt1)){
					    	Map m = util.manualSave1(sbt1, conn);
					    	manager.createSystemRelationObject(obj.id(),"APP_XFHANDLER", (String) m.get("HID"));
					    }
			    	}
			    	
			    	
			    }
			
			    
			    
			}

			} catch (Exception ex) {
	            ISystem.catchException(request, this, ex);
	        }
			
            IRole role = null;

            if (LFTYPE.equals("0")) {
                /*街乡来信由街乡信访办人员统一办理*/
                role = rm.getRoleByKey("jxxfbuser");
            } else if (LFTYPE.equals("1")) {
                /*区来信由街乡信访办人员统一办理*/
                role = rm.getRoleByKey("quxfbuser");
            }

            /*信访系统管理员*/
            IRole xfManager = rm.getRoleByKey("xfmanager");

            IUser user = ISystem.getSessionUser(request);


            try {
                /*对信访办角色进行授权,可以对该来访进行办理*/
                pm.insert(obj.id(), obj.iname(), obj.ikey(), "ISYS_OBJECT", 3,
                    role.id(), role.iname(), "role", user, false);

                /*对信访系统管理员角色进行授权,可以对来信进行编辑\删除\查阅*/
                pm.insert(obj.id(), obj.iname(), obj.ikey(), "ISYS_OBJECT", 3,
                    xfManager.id(), xfManager.iname(), "role", user, false);
            } catch (Exception ex) {
                throw new MachiningException("purview for object error.", ex);
            }

            try {
                LogManager lm = new LogManager(conn);
                lm.log(user, lfid, "2", "qtfdj", "");
            } catch (Exception ex) {
                throw new MachiningException("log lfdj error.", ex);
            }
            


        }

        return null;
    }
    
    /**
     * 验证派遣记录是否已存在
     * @param xfblInfoList
     * @param xfblInfo
     * @return
     */
    private boolean isAlreadyExist(List<Map> xfblInfoList,SimpleBean4Table xfblInfo){
    	boolean result = true;
    	
    	for(Map xfbl:xfblInfoList){
    		
    		if((String)xfbl.get("H_GROUPID")!= null && ((String)xfbl.get("H_GROUPID")).equals(xfblInfo.getResource().get("H_GROUPID"))){
    			return true;
    		}else{
    			result = false;
    			
    		};  		
    		
    	}
    	return result;
    }
    
    /**
     * 查找部门表中的部门
     * @param conn
     * @param flumenames
     */
    private Map<String,String> searchSingleDept(Connection conn,String flumenames){
    	
    	String sql = "SELECT * FROM ISYS_DEPARTMENT WHERE FLUMENAMES = ?";

        DataTrimmerI trimmer = new DataTrimmerI(conn);

        DataTrimmerI.DataItemList dil = trimmer.createDIL();

        dil.set(flumenames);

        Map<String,String> hdlMap = trimmer.searchSingleData(sql, dil);
        
        return hdlMap;
    	
    }
    
    /**
     * 查询社区/行政村
     * @param conn
     * @param flumenames
     * @return
     */
    private List<Map> searchMultiDept(Connection conn,String flumenames){
    	
    	String sql = "SELECT * FROM ISYS_DEPARTMENT WHERE FLUMENAMES = ?";

        DataTrimmerI trimmer = new DataTrimmerI(conn);

        DataTrimmerI.DataItemList dil = trimmer.createDIL();

        dil.set(flumenames);

        List<Map>  resultList= trimmer.searchMultiData(sql, dil);
        
        return resultList;
    	
    }
}
